<?php


namespace common\helpers;

use yii;
use yii\helpers\Json;
use yii\web\Response;
use yii\web\UnprocessableEntityHttpException;

class CommonHelper
{
    /**
     * 返回json数据格式
     *
     * @param int $code 状态码
     * @param string $message 返回的报错信息
     * @param array|object $data 返回的数据结构
     * @return array
     */
    public static function json($code = 404, $message = '未知错误', $data = [])
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $result = [
            'code' => strval($code),
            'message' => trim($message),
            'data' => $data ? ArrayHelper::toArray($data) : [],
        ];

        return $result;
    }

    /**
     * 返回 array 数据格式 api 自动转为 json
     *
     * @param int $code 状态码 注意：要符合http状态码
     * @param string $message 返回的报错信息
     * @param array|object $data 返回的数据结构
     * @return mixed
     */
    public static function api($code = 404, $message = '未知错误', $data = [])
    {
        Yii::$app->response->setStatusCode($code, $message);
        Yii::$app->response->data = $data ? ArrayHelper::toArray($data) : [];

        return Yii::$app->response->data;
    }

    /**
     * @apiName 根据key 批量提取value
     * @apiGroup
     * @apiParam {Number}
     * @apiParam {String}
     * @author loujie
     * @param array $list
     * @param array $array
     * @return array
     */
    public static function link_array_key_value($list=array(),$array=array())
    {
        //从键值对中获取对应的数据
        foreach ($list as $k => $v)
        {
            if(isset($array[$v]))
            {
                $list[$k]=$array[$v];
            }else
            {
                unset($list[$k]);
            }
        }
        return $list;
    }

    /**
     * 获取设备客户端信息
     *
     * @return mixed|string
     */
    public static function detectVersion()
    {
        /** @var \Detection\MobileDetect $detect */
        $detect = Yii::$app->mobileDetect;

        if ($detect->isMobile()) {
            $devices = $detect->getOperatingSystems();
            $device = '';

            if (!empty($devices)) {
                foreach ($devices as $key => $valaue) {
                    if ($detect->is($key)) {
                        $device = $key . $detect->version($key);
                        break;
                    }
                }
            }

            return $device;
        }

        return $detect->getUserAgent();
    }
    /**
     * 获取文件路径
     * @param string $url
     * @return string
     */
    public static function getFileUrlPath(string $url): string
    {
        if (empty($url)) {
            return $url;
        }

        $index = strpos($url, '/juliao/');
        if ($index === false) {
            return '';
        }

        return substr($url, $index);
    }

    /**
     * 获取文件配置url
     * @param string $url
     * @return string
     */
    public static function getFileConfigUrl(string $url): string
    {
        if (empty($url)) {
            return $url;
        }

        $path = self::getFileUrlPath($url);
        if (empty($path)) {
            return $url;
        }

        return Yii::$app->params['robot_image_host'] . $path;
    }

    /**
     * 解析消息内容【添加配置url】
     * @param string $content
     * @return string
     */
    public static function parseMessageContent(string $content): string
    {
        $wxid = '';
        $newContent = json_decode($content, true);
        if (is_array($newContent) === false) {
            $contentArr = explode(':', $newContent, 2);
            if (count($contentArr) < 2) {
                return self::getFileConfigUrl($content);
            }
            $wxid = $contentArr[0] . ':';
            $newContent = json_decode($contentArr[1], true);
            if (is_array($newContent) === false) {
                return self::getFileConfigUrl($content);
            }
        }

        if (isset($newContent['fileUrl'])) {
            $newContent['fileUrl'] = self::getFileConfigUrl($newContent['fileUrl']);
        }
        if (isset($newContent['Thumb'])) {
            $newContent['Thumb'] = self::getFileConfigUrl($newContent['Thumb']);
        }
        return $wxid . json_encode($newContent);
    }

    /**
     * @apiName 获取操作系统
     * @param $agent
     * @return bool|string
     */
//    public static function get_os(){
//            $os = false;
//
//            $agent = Yii::$app->mobileDetect->getUserAgent();
//
//            if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent))
//            {
//              $os = 'Windows Vista';
//            }
//            else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent))
//            {
//              $os = 'Windows 7';
//            }
//              else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent))
//            {
//              $os = 'Windows 8';
//            }else if(preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent))
//            {
//              $os = 'Windows 10';#添加win10判断
//            }else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent))
//            {
//              $os = 'Windows XP';
//            }
//            else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent))
//            {
//              $os = 'Windows 2000';
//            }
//            else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent))
//            {
//              $os = 'Windows NT';
//            }
//            else if (preg_match('/linux/i', $agent))
//            {
//              $os = 'Linux';
//                    if ( preg_match( '/Android.([0-9. _]+)/i', $agent, $matches ) ) {
//                    $os = 'Android';
//                } elseif ( preg_match( '#Ubuntu#i', $agent ) ) {
//                    $os = 'Ubuntu';
//                } elseif ( preg_match( '#Debian#i', $agent ) ) {
//                    $os = 'Debian';
//                } elseif ( preg_match( '#Fedora#i', $agent ) ) {
//                    $os = 'Fedora';
//                }
//            }
//            else if (preg_match('/unix/i', $agent))
//            {
//              $os = 'Unix';
//            }
//            else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent))
//            {
//              $os = 'SunOS';
//            }
//            else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent))
//            {
//              $os = 'IBM OS/2';
//            }
//            else if (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent))
//            {
//              $os = 'Macintosh';
//            }
//            else if (preg_match('/PowerPC/i', $agent))
//            {
//              $os = 'PowerPC';
//            }
//            else if (preg_match('/AIX/i', $agent))
//            {
//              $os = 'AIX';
//            }
//            else if (preg_match('/HPUX/i', $agent))
//            {
//              $os = 'HPUX';
//            }
//            else if (preg_match('/NetBSD/i', $agent))
//            {
//              $os = 'NetBSD';
//            }
//            else if (preg_match('/BSD/i', $agent))
//            {
//              $os = 'BSD';
//            }
//            else if (preg_match('/OSF1/i', $agent))
//            {
//              $os = 'OSF1';
//            }
//            else if (preg_match('/IRIX/i', $agent))
//            {
//              $os = 'IRIX';
//            }
//            else if (preg_match('/FreeBSD/i', $agent))
//            {
//              $os = 'FreeBSD';
//            }
//            else if (preg_match('/teleport/i', $agent))
//            {
//              $os = 'teleport';
//            }
//            else if (preg_match('/flashget/i', $agent))
//            {
//              $os = 'flashget';
//            }
//            else if (preg_match('/webzip/i', $agent))
//            {
//              $os = 'webzip';
//            }
//            else if (preg_match('/offline/i', $agent))
//            {
//              $os = 'offline';
//            }
//            else
//            {
//              $os = '未知操作系统';
//            }
//            return $os;
//        }


    /**
     * 获取访客操作系统
     *
     * @return string
     */
    public static function get_os()
    {
        $userAgent = Yii::$app->mobileDetect->getUserAgent();

        static $touchBrowserList = [
            'iphone',
            'phone',
            'mobile',
            'wap',
            'netfront',
            'java',
            'opera mobi',
            'HM NOTE',
            'opera mini',
            'ucweb',
            'windows ce',
            'symbian',
            'series',
            'webos',
            'sony',
            'dopod',
            'blackberry',
            'nokia',
            'samsung',
            'palmsource',
            'xda',
            'pieplus',
            'meizu',
            'midp',
            'cldc',
            'motorola',
            'foma',
            'docomo',
            'up.browser',
            'up.link',
            'blazer',
            'helio',
            'hosin',
            'huawei',
            'novarra',
            'coolpad',
            'webos',
            'techfaith',
            'palmsource',
            'amoi',
            'alcatel',
            'ktouch',
            'nexian',
            'ericsson',
            'philips',
            'sagem',
            'wellcom',
            'maui',
            'bunjalloo',
            'smartphone',
            'iemobile',
            'spice',
            'bird',
            'longcos',
            'pantech',
            'R7c',
            'gionee',
            'portalmmm',
            'jig browser',
            'hiptop',
            'benq',
            'haier',
            '^lct',
            '320x320',
            '240x320',
            '176x220',
            'windows phone',
            'zte-',
            'KOPO',
            'MI',
            'm1',
            'm2',
            'ATH',
            'iToolsVM',
            'HUAWEI',
            'SM-C5000',
            'KTU84P',
            'OPPO',
            'EVA-',
            'SM-',
            'PE-TL10',
            'HTC',
            'vivo',
            'H60-',
            'Nexus',
            'HLJ-XM-E2',
            'ZTE',
            'UOOGOU',
            'NX531J',
            'Redmi',
            'HS-X68T',
            'A51',
            'SCL-',
            'A31c',
            'Le',
            'BLN-',
            'ZUK',
            'KIW-',
            'GT-',
            'SAMSUNG',
            'Android',
        ];

        static $wmlBrowserList = [
            'cect',
            'compal',
            'ctl',
            'lg',
            'nec',
            'tcl',
            'alcatel',
            'ericsson',
            'bird',
            'daxian',
            'dbtel',
            'eastcom',
            'pantech',
            'dopod',
            'philips',
            'haier',
            'konka',
            'kejian',
            'lenovo',
            'benq',
            'mot',
            'soutec',
            'nokia',
            'sagem',
            'sgh',
            'sed',
            'capitel',
            'panasonic',
            'zte',
            'sharp',
            'amoi',
            'panda',
            'sonyericsson',
        ];

        static $padList = ['ipad'];

        static $wexin = ['MicroMessenger'];

        $brower = [
            '/Windows NT 10.0/i' => 'Windows 10',
            '/Windows NT 6.3/i' => 'Windows 8.1',
            '/Windows NT 6.2/i' => 'Windows 8',
            '/Windows NT 6.1/i' => 'Windows 7',
            '/Windows NT 6.0/i' => 'Windows Vista',
            '/Windows NT 5.2/i' => 'Windows Server 2003/XP x64',
            '/Windows NT 5.1/i' => 'Windows XP',
            '/Windows xp/i' => 'Windows XP',
            '/Windows NT 5.0/i' => 'Windows 2000',
            '/Windows me/i' => 'Windows ME',
            '/win98/i' => 'Windows 98',
            '/win95/i' => 'Windows 95',
            '/win16/i' => 'Windows 3.11',
            '/mac_powerpc/i' => 'Mac OS X 9',
            '/macintosh|mac os x/i' => 'Mac OS X', //'/linux/i' => 'Linux',
            '/unix/i' => 'Unix',
            '/bsd/i' => 'BSD',
            '/ubuntu/i' => 'Ubuntu',
        ];

        if ($v = self::dstrpos($userAgent, $padList, true)) {
            return $v;
        } elseif (($v = self::dstrpos($userAgent, $touchBrowserList, true))) {
            return $v;
        } elseif (($v = self::dstrpos($userAgent, $wmlBrowserList))) {
            return $v;
        } else {
            foreach ($brower as $regex => $value) {
                if (preg_match(strtolower($regex), strtolower($userAgent))) {
                    return $value;
                }
            }
        }
    }

    public static function dstrpos($string, $arr, $returnValue = false)
    {
        if (empty($string)) {
            return false;
        }

        foreach ((array)$arr as $v) {
            if (strpos($string, $v) !== false) {
                $return = $returnValue ? $v : true;

                return $return;
            }
        }

        return false;
    }


    /**
     * @apiName 获取浏览器信息
     * @apiGroup
     * @param $sys USER_AGENT
     * @return string
     */
//    public static function get_bro(){
//
//        $sys = Yii::$app->mobileDetect->getUserAgent();
//        if (stripos($sys, "Firefox/") > 0) {
//            preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
//            $exp[0] = "Firefox";
//            $exp[1] = $b[1];  //获取火狐浏览器的版本号
//        } elseif (stripos($sys, "Maxthon") > 0) {
//            preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
//            $exp[0] = "傲游";
//            $exp[1] = $aoyou[1];
//        } elseif (stripos($sys, "MSIE") > 0) {
//            preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
//            $exp[0] = "IE";
//            $exp[1] = $ie[1];  //获取IE的版本号
//        } elseif (stripos($sys, "OPR") > 0) {
//            preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
//            $exp[0] = "Opera";
//            $exp[1] = $opera[1];
//        } elseif(stripos($sys, "Edge") > 0) {
//            //win10 Edge浏览器 添加了chrome内核标记 在判断Chrome之前匹配
//            preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
//            $exp[0] = "Edge";
//            $exp[1] = $Edge[1];
//        } elseif (stripos($sys, "Chrome") > 0) {
//            preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
//            $exp[0] = "Chrome";
//            $exp[1] = $google[1];  //获取google chrome的版本号
//        } elseif(stripos($sys,'rv:')>0 && stripos($sys,'Gecko')>0){
//            preg_match("/rv:([\d\.]+)/", $sys, $IE);
//            $exp[0] = "IE";
//            $exp[1] = $IE[1];
//        }else {
//            $exp[0] = "未知浏览器";
//            $exp[1] = "";
//        }
//        return $exp[0].'('.$exp[1].')';
//    }

    public static function get_bro()
    {
        $agent = $_SERVER["HTTP_USER_AGENT"] ?? '';

        if ((strpos($agent, 'Firefox') !== false) && preg_match('/FireFox\/(\d+)\..*/i', $agent, $regs)) {
            /* Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:49.0) Gecko/20100101 Firefox/49.0 */
            return "Firefox " . $regs[1];
        } elseif (strpos($agent, 'SE 2.X MetaSr') !== false) {
            if (strpos($agent, 'rv:11.0')) {
                /* Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0; SE 2.X MetaSr 1.0) like Gecko */
                return "搜狗高速浏览器 IE 11兼容模式";
            } else {
                /* Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0 */
                return "搜狗高速浏览器";
            }
        } elseif ((strpos($agent, 'Maxthon') !== false) && preg_match('/Maxthon\/(\d.+)\\s/i', $agent, $regs)) {
            /* Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.9.4.1000 Chrome/39.0.2146.0 Safari/537.36 */
            return "Maxthon  " . explode('Chrome', $regs[1])[0];
        } elseif ((strpos($agent, 'BIDUBrowser') !== false) && preg_match('/BIDUBrowser\/(\d.+)\\s.*/i', $agent, $regs)) {
            /* Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 BIDUBrowser/8.6 Safari/537.36 */
            return "BIDUBrowser  " . $regs[1];
        } elseif ((strpos($agent, 'QQBrowser') !== false) && preg_match('/QQBrowser\/(\d.+)\..*/i', $agent, $regs)) {
            /* Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.95 Safari/537.36 Core/1.50.1414.400 QQBrowser/9.5.9244.400 */
            return "QQBrowser " . $regs[1];
        } elseif ((strpos($agent, 'LBBROWSER') !== false)) {
            /* Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko LBBROWSER */
            if (strpos($agent, 'rv:11.0')) {
                return "猎豹浏览器 IE 11兼容模式";
            } else {
                /* Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER */
                return "猎豹浏览器";
            }
        } elseif ((strpos($agent, 'Edge') !== false) && preg_match('/Edge\/(\d.+)\\s*/i', $agent, $regs)) {
            /* Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393 */
            return "Microsfot Edge " . $regs[1];
        } elseif ((strpos($agent, 'Opera') !== false) && preg_match('/Opera[\s|\/](\d+)\..*/i', $agent, $regs)) {
            return 'Opera ' . $regs[1];
        } elseif ((strpos($agent, 'OPR') !== false) && preg_match('/OPR[\s|\/](\d.+)\\s*/i', $agent, $regs)) {
            /* Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 OPR/40.0.2308.90 */
            return 'Opera ' . $regs[1];
        } elseif ((strpos($agent, 'Chrome') !== false) && preg_match('/Chrome\/(\d.+)\\s.*/i', $agent, $regs)) {
            /* Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36 */
            return "Chrome " . $regs[1];
        } elseif (((strpos($agent, 'Chrome') == false) && strpos($agent, 'Safari') !== false) && preg_match('/Version\/(\d.+)\\s.*$/i', $agent, $regs)) {
            /* Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Safari/602.1.50 */
            return 'Safari ' . $regs[1];
        } elseif (strpos($agent, 'MSIE') !== false || strpos($agent, 'rv:11.0')) {
            return "IE 11";
        } else {
            return 'Unknown';
        }
    }

    /**
     * 解析错误
     *
     * @param $firstErrors
     * @return bool|string
     */
    public static function analyErr($firstErrors)
    {
        if (!is_array($firstErrors) || empty($firstErrors)) {
            return false;
        }

        $errors = array_values($firstErrors)[0];
        return $errors ?? '未捕获到错误信息';
    }

    /**
     * 解析微信是否报错
     *
     * @param $message  微信回调数据
     * @param bool $direct 是否直接报错
     * @return bool|mixed
     * @throws UnprocessableEntityHttpException
     */
    public static function getWechatError($message, $direct = true)
    {
        if (isset($message['errcode']) && $message['errcode'] != 0) {
            // token过期 强制重新从微信服务器获取 token.
            if ($message['errcode'] == 40001) {
                \Yii::$app->wechat->app->access_token->getToken(true);
            }

            if ($direct) {
                throw new UnprocessableEntityHttpException($message['errmsg']);
            }

            return $message['errmsg'];
        }

        return false;
    }

    /**
     * @return false|string
     * @throws yii\base\InvalidConfigException
     */
    public static function getUrl()
    {
        $url = explode('?', Yii::$app->request->getUrl())[0];
        $matching = '/' . Yii::$app->id . '/';
        if (substr($url, 0, strlen($matching)) == $matching) {
            $url = substr($url, strlen($matching), strlen($url));
        }

        return $url;
    }

    /**
     * @param $value
     * @return mixed
     */
    public static function htmlEncode($value)
    {
        if (!is_array($value)) {
            $value = Json::decode($value);
        }

        $array = [];
        foreach ($value as $key => &$item) {
            if (!is_array($item)) {
                $array[$key] = Html::encode($item);
            } else {
                $array[$key] = self::htmlEncode($item);
            }
        }

        return $array;
    }

    /**
     * @param $ip
     * @param bool $long
     * @return bool|string
     */
    public static function analysisIp($ip, $long = true)
    {
        if (empty($ip)) {
            return false;
        }

        if ('127.0.0.1' == $ip) {
            return '本地';
        }

        if ($long === true) {
            if (((int)$ip) > 1000) {
                return '无法解析';
            }
        }

        $ipData = \Zhuzhichao\IpLocationZh\Ip::find($ip);

        $str = '';
        isset($ipData[0]) && $str .= $ipData[0];
        isset($ipData[1]) && $str .= ' · ' . $ipData[1];
        isset($ipData[2]) && $str .= ' · ' . $ipData[2];

        return $str;
    }

    /**
     * 获取随机user_agent
     *
     * @param string $mobile
     * @return mixed
     * @author huige
     */
    public static function getUserAgent($mobile = '')
    {
        $appAgentList = [
            //'HUAWEI_Y220T_TD/1.0 Android/2.3.5 SC8810_CMCC/W12.06.21 Release/06.22.2012 Browser/AppleWebkit533.1',  // 该地址不支持抖音采集，仅用于错误测试使用
            'Mozilla/5.0 (Linux; Android 8.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4 (compatible; Baiduspider/2.0;)',
            'Mozilla/5.0 (Linux; U; Android 8.1.0; zh-CN; EML-AL00 Build/HUAWEIEML-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 baidu.sogo.uc.UCBrowser/11.9.4.974 UWS/2.13.1.48 Mobile Safari/537.36 AliApp(DingTalk/4.5.11) com.alibaba.android.rimet/10487439 Channel/227200 language/zh-CN',
            'Mozilla/5.0 (Linux; Android 8.1.1; SM801 Build/LMY47V; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQ    QBrowser/6.2 TBS/043024 Safari/537.36 MicroMessenger/6.5.4.1000 NetType/4G Language/zh_CN',
            'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Mobile Safari/537.36',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12A365 Safari/600.1.4',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B435',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Mobile/10B350',
            'MOFOTO T6908LS Linux/3.0.13 Android/8.1.0 Release/01.10.2013 Browser/AppleWebKit534.30 Profile/MIDP-2.0 Configuration/CLDC-1.1 Mobile Safari/534.30 Android 4.0.1',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B206',
            'vivo_Y613/1.0 Linux/3.4.5 Android/9.0.0 Release/01.17.2014 Browser/AppleWebKit534.30 Profile/MIDP-2.0 Configuration/CLDC-1.1 Mobile Safari/534.30 Android 4.2.2',
            'Mozilla/5.0 (iPad AirWIFI; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/6.0 MQQBrowser/5.5.1 Mobile/12B410 Safari/8536.25',
            'Mozilla/5.0 (iPad; CPU OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B410 iPad2,5__weibo__3.6.0__ipad__os8.1',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B411 ',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B435 MicroMessenger/6.0.1 NetType/WIFI',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B435 QQ/5.2.1.302 NetType/WIFI Mem/30',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B435_TencentMicroBlogiPhone_TXMicroBlog510',
        ];

        $pcAgentList = [
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetTy    pe/WIFI WindowsWechat QBCore/3.43.27.400 QQBrowser/9.0.2524.400',
            'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
            'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.20 (KHTML, like Gecko) Chrome/11.0.672.0 Safari/534.20',
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.8.0.11) Firefox/1.5.0.11',
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15',
            'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.33 Safari/534.3 SE 2.X MetaSr 1.0',
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.34 Safari/534.24 XiaoMi/MiuiBrowser/2.0.1',
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.0.0 Safari/537.36',
            'Mozilla/5.0 (X11; Linux x86_64; rv:10.0.12) Gecko/20130104 Firefox/10.0.12',
            'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0',
            'MQQBrowser/2.5.1 Mozilla/5.0 (iPad; CPU OS 6_0_1 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Mobile/10A523 Safari/7534.48.3',
            'MQQBrowser/4.2/Mozilla/5.0 (Linux; U; Android 4.2.2; zh-cn; AOLE Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
            'Opera/9.80 (Linux armv7l; InettvBrowser/2.2 (00014A;SonyDTV140;0001;0001) KDL60W850B; CC/CHN) Presto/2.12.407 Version/12.50',
        ];

        switch ($mobile) {
            case 'app':
                $userAgentList = $appAgentList;
                break;
            case 'pc':
                $userAgentList = $pcAgentList;
                break;
            default:
                $userAgentList = array_merge($appAgentList, $pcAgentList);
                break;
        }

        return $userAgentList[array_rand($userAgentList, 1)];
    }

    /**
     * @param $url
     * @param string $saveDir
     * @param string $fileName
     * @return array|bool
     * @author huige
     */
    public static function downCurl($url, $saveDir = '', $fileName = '')
    {
        if (trim($url) == '') {
            return false;
        }

        if (trim($saveDir) == '') {
            $saveDir = './';
        }

        if (0 !== strrpos($saveDir, '/')) {
            $saveDir .= '/';
        }

        // 创建保存目录
        if (!file_exists($saveDir) && !mkdir($saveDir, 0777, true)) {
            return false;
        }

        // 获取远程文件所采用的方法
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        $fp = fopen($saveDir . $fileName, 'w+');
        curl_setopt($curl, CURLOPT_FILE, $fp);
        // 这个选项是意思是跳转，如果你访问的页面跳转到另一个页面，也会模拟访问。
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 50);

        curl_exec($curl);
        curl_close($curl);
        fclose($fp);

        return [
            'file_name' => $fileName,
            'save_path' => $saveDir . $fileName
        ];
    }

    /**
     * 根据URL获取文件大小
     *
     * @param $url
     * @return bool|string
     * @author huige
     */
    public static function getFileSize($url)
    {
        $url = parse_url($url);

        if (empty($url['host'])) {
            return false;
        }

        $url['port'] = empty($url['post']) ? 80 : $url['post'];
        $url['path'] = empty($url['path']) ? '/' : $url['path'];

        $fp = fsockopen($url['host'], $url['port'], $error);

        if ($fp) {
            fputs($fp, "GET " . $url['path'] . " HTTP/1.1\r\n");
            fputs($fp, "Host:" . $url['host'] . "\r\n\r\n");

            while (!feof($fp)) {
                $str = fgets($fp);
                if (trim($str) == '') {
                    break;
                } elseif (preg_match('/Content-Length:(.*)/si', $str, $arr)) {
                    return trim($arr[1]);
                }
            }
            fclose($fp);
            return false;
        } else {
            return false;
        }
    }

    /**
     * 获取文章内容中所有图片Url
     *
     * @param $content
     * @return array|mixed
     * @author chenyuebin
     */
    public static function getContentImg($content='')
    {
        $preg = '/<img.*?src=[\"|\']?(.*?)[\"|\']>/i';
        preg_match_all($preg, $content, $match);
        $count = count($match[1]);
        if ($count > 0) {
            return $match[1];
        }
        return Yii::$app->params['api_url'] . '/images/common/default_img.png';
    }

    /**
     * curl  https请求
     *
     * @param $url
     * @param null $data
     * @return bool|string
     * @author chenyuebin
     */
    public static function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 生成随机码
     *
     * @param int $count 长度
     * @param string $chars 随机字符串【不填，则默认】
     * @param int $unique 随机字符串是否唯一【1是、0否】
     * @return array|string
     */
    public static function getRandomAuthKey(int $count = 6, string $chars='', int $unique = 0)
    {
        $chars = $chars ? $chars : '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        if ($unique) {
            $tmp = range(0, strlen($chars)-1);
            shuffle($tmp);
            $keys = array_slice($tmp, 0, $count);
            unset($tmp);
        } else {
            $keys = array_rand(range(0, strlen($chars)-1), $count);
        }

        $buff = array();
        foreach($keys as $value) {
            $buff[] = $chars{$value};
        }

        return implode('', $buff);
    }

    /**
     * 抛出异常结果
     *
     * @param \Exception $e
     * @return array
     */
    public static function throwRes(\Exception $e): array
    {
        $code = $e->getCode() ?: 422;
        return self::json($code, $e->getMessage());
    }

    /**
     * rpc推送消息
     * @param string $serviceName
     * @param string $moduleName
     * @param string $actionName
     * @param array $arg
     */
    public static function rpcRequest(string $serviceName, string $moduleName, string $actionName, array $arg):void
    {
        $data = [
            'service' => $serviceName, // 需要调用的服务名称
            'module'  => $moduleName, // 需要调用的服务下的子模块名称
            'action'  => $actionName,  // 需要调用的服务下的子模块的方法名称
            'arg'     => $arg, // 需要传递的参数
        ];
//        $raw = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $raw = json_encode($data);
        $fp = stream_socket_client('tcp://'.Yii::$app->params['ws.host']);
        fwrite($fp, pack('N', strlen($raw)) . $raw); // pack 数据校验
        fclose($fp);
    }

    /**
     * 灯塔接口请求
     * @param string $url
     * @param array $params
     * @param $data
     * @param $header
     * @return array
     * @throws \Exception
     */
    public static function dengta_request(string $url, array $params = [], $data = null, $header = null)
    {
        $url = Yii::$app->params['dengta_host'] . $url;
        $params['auth_project_id'] = Yii::$app->params['project_id'];
        if ($params) {
            $query = http_build_query($params);
            $url .= "?{$query}";
        }
        if ($data) {
            $data = http_build_query($data);
//            $header = ["content-type:application/json; charset=UTF-8"];
        }
        $res = self::https_request($url, $data, $header);
//        var_dump($url);exit();
        $resArr = json_decode($res, true);
//        var_dump($resArr);exit();
        if (empty($resArr) || $resArr['code'] != 200) {
            throw new \Exception($resArr['message'] ?? '灯塔获取失败', $resArr['code']);
        }
        return $resArr['data'];
    }
}
